package com.heer.gymnasium.module.my.views;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.module.my.beans.FaceBean;
import com.heer.gymnasium.util.Base64Util;
import com.heer.gymnasium.util.DialogUtils;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.gymnasium.util.PermissionUtils;
import com.heer.gymnasium.util.SDCardUtils;
import com.heer.gymnasium.util.ScreenUtils;
import com.heer.gymnasium.util.StringUtils;
import com.zhihuiyun.library.utils.BitmapUtils;
import com.zhihuiyun.library.utils.L;

import java.io.File;
import java.io.FileNotFoundException;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

import static android.R.attr.bitmap;
import static android.R.attr.targetSdkVersion;

/**
 * Created by yan on 2018/1/18.
 * 面部识别界面
 */

public class FaceActivity extends BaseActivity {
    private static final int SELECT_ID = R.id.layout_face_select_tv;
    private static final int HINT_ID = R.id.layout_face_hint_tv;
    private static final int HEAD_ID = R.id.layout_face_head_iv;
    private static final int REQUEST_CODE_CAPTURE = 1;
    private static final int REQUEST_CODE_PICK_IMAGE = 2;

    @BindView(SELECT_ID)
    TextView selectTextView;
    @BindView(HINT_ID)
    TextView hintTextView;
    @BindView(HEAD_ID)
    ImageView headhintImageView;

    private Uri imageUri;

    /**
     * TODO 界面跳转，传参需定义
     *
     * @param context
     */
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, FaceActivity.class);
        context.startActivity(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.layout_face);
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setTitleText("面部识别");
        titleUtils.startMainActivity(this);
        svProgressHUD = new SVProgressHUD(this);

    }

    @Override
    protected void loadData() {
        super.loadData();
        getUserFacePhoto();
    }

    //     获取头像信息
    private void getUserFacePhoto() {
        SignHelper signHelper = new SignHelper("");
        mAppHelper.apiService().getUserFacePhoto(signHelper.getToken()).enqueue(new BaseCallback<ApiResponse<FaceBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<FaceBean>> call, Response<ApiResponse<FaceBean>> response) {
                FaceBean bean = response.body().getData();
                if (!TextUtils.isEmpty(bean.getFace1())) {
                    selectTextView.setVisibility(View.INVISIBLE);
                    if (Util.isOnMainThread()) {
                        Glide.with(mContext).load(bean.getFace1()).into(headhintImageView);
                    }
                } else {
                    selectTextView.setVisibility(View.VISIBLE);
                }
            }


        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (Util.isOnMainThread() && !Glide.with(this).isPaused()) {
            Glide.with(this).pauseRequests();

        }
    }

    //上传面部识别
    private void faceCheck(String base64Url) {
        svProgressHUD.showWithStatus("加载中");
        mAppHelper.apiService().facecheck(base64Url, "jpg").enqueue(new BaseCallback<ApiResponse<String>>() {
            @Override
            public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                getUserFacePhoto();
                svProgressHUD.dismiss();
            }

            @Override
            public void onError(Call<ApiResponse<String>> call, Throwable t) {
                super.onError(call, t);
                svProgressHUD.dismiss();
            }
        });
    }

    @OnClick(SELECT_ID)
    public void selectOnClick() {
        if (PermissionUtils.selfPermissionGranted(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            PermissionUtils.openPermission(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PermissionUtils.PERMISSION_CODE_5);
        } else {
            popup();
        }
    }


    private SVProgressHUD svProgressHUD;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAPTURE) {
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");

            bitmap = BitmapUtils.resizeBitmap(bitmap, 480);
            faceCheck(Base64Util.bitmapToBase64(bitmap));

        } else if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (data == null)
                return;

            Uri uri = data.getData();
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                L.e(" bitmap 大小 " + bitmap.getRowBytes() * bitmap.getHeight());
                faceCheck(Base64Util.bitmapToBase64(bitmap));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtils.PERMISSION_CODE_5) {
            popup();
        } else if (requestCode == PermissionUtils.PERMISSION_CODE_6) {
            takePhoto();
        }


    }

    /**
     * 打开拍照
     */
    private void takePhoto() {
        File file = new File(SDCardUtils.getHeadPath(this));
        if (!file.exists()) {
            file.mkdirs();
        }
        File headFile = new File(file, "head.jpg");

//        try {
//            if (headFile.exists()) {
//                headFile.delete();
//            }
//            headFile.createNewFile();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        /**
         * 隐式打开拍照的Activity，并且传入CROP_PHOTO常量作为拍照结束后回调的标志
         * 将文件转化为uri
         */
//        imageUri = Uri.fromFile(headFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_CODE_CAPTURE);
        }

    }

    /**
     * 打开选择图片的界面
     */
    void choosePhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);

    }

    /**
     * 选择照片popup
     */
    public void popup() {
        PopupWindow window = DialogUtils.getPopupWindow(this, R.layout.popop_camara, new DialogUtils.DialogCallBack() {
            @Override
            public void callBack(View view, final PopupWindow popupWindow) {

                view.findViewById(R.id.popup_camare_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();
                        if (Build.VERSION.SDK_INT >= 23) {
                            if (PermissionUtils.selfPermissionGranted(FaceActivity.this, Manifest.permission.CAMERA)) {
                                PermissionUtils.openPermission(FaceActivity.this, new String[]{Manifest.permission.CAMERA},
                                        PermissionUtils.PERMISSION_CODE_6);
                                return;
                            } else {
                                takePhoto();//调用具体方法
                            }
                        } else {
                            takePhoto();//调用具体方法
                        }
                    }
                });
                view.findViewById(R.id.popup_camare_picture_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();
                        choosePhoto();
                    }
                });
                view.findViewById(R.id.popup_camare_cancel_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();
                    }
                });
            }
        });
        window.showAtLocation(selectTextView, Gravity.BOTTOM, 0, ScreenUtils.getScreenH());
    }

}
